package com.xs.demo.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;





import com.xs.demo.entity.Userinfo;
/**
 * SpringMVC+Hibernate +MySql+ EasyUI ---CRUD
 * @author 宗潇帅
 * 类名称：UserDao 
 * @date 2014-11-15 下午4:34:51 
 * 备注：
 */
public class UserDao extends BaseDao{

	public List<Map<String, Object>> list(String name,int start, int size,
			String order) {
		List<Object> param = new ArrayList<Object>();
		String sql = "select u.* from userinfo u where 1=1 ";
		if(null != name && name.trim().length() > 0){
			sql += " and u.name like ? ";
			param.add("%"+name+"%");
		}
		if(null == order || order.length() == 0){
			order = " birthday asc";
		}
		return super.listByNative(sql, param.toArray(), start, size, order);
	}
	public List<Userinfo> listfindAll() {
		List<Object> param = new ArrayList<Object>();
		String hql = "from Userinfo";
		return super.list(hql, param.toArray());
	}

	public int count(String name,int start, int size,
			String order) {
		List<Object> param = new ArrayList<Object>();
		String sql = "select count(*) from userinfo u where 1=1 ";
		if(null != name && name.trim().length() > 0){
			sql += " and u.name like ? ";
			param.add("%"+name+"%");
		}
		return super.countByNative(sql, param.toArray());
	}

	@SuppressWarnings("unchecked")
	public Userinfo getUserByName(String name) {
		String hql="select u from Userinfo u where u.name=? ";
		List<Userinfo> list=super.list(hql, new Object[]{name});
		if(list!=null&&list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}
	public List<Map<String, Object>> listAll(){
		String sql = "select u.name,u.age,u.address from userinfo u";
		return jdbcTemplate.queryForList(sql);
	}
	public Map listAllU(){
		String sql = "select u.name,u.age,u.address from userinfo u limit 1";
			
			return  jdbcTemplate.queryForMap(sql);
		
	}
	@SuppressWarnings("unchecked")
	public List<Userinfo> listByUP(String username, String password) {
		String hql = "from Userinfo where name = ? and password = ? ";
		return super.list(hql, new Object[]{username,password});
	}
	public List<Userinfo> lists(Userinfo userinfo) {
		return super.list(Userinfo.class);
	}
	
	public int[] insertuserinfo(final List<Userinfo> list){
		String sql = "insert into userinfo(id,name) values(null,?)";
		return jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int index) throws SQLException {
				Userinfo userinfo = list.get(index);
				ps.setString(1, userinfo.getName());
			}
			@Override
			public int getBatchSize() {
				return list.size();
			}
		});
	}


}
